package com.jessechanrui.template.thread.factory;

import com.jessechanrui.template.thread.ThreadUtil;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenrui
 * @date 2024/12/25
 */
public class CustomThreadFactory implements ThreadFactory {

    static AtomicInteger threadNo = new AtomicInteger(1);

    private String name = "自定义线程工厂";
    public CustomThreadFactory() {
    }

    public CustomThreadFactory(String name) {
        this.name = name;
    }

    @Override
    public Thread newThread(Runnable target) {
        String threadName = name + "-" + threadNo.get();
        ThreadUtil.print("创建一条线程， 名称为： " + threadName);
        threadNo.incrementAndGet();
        //设置线程名称和异步执行目标
        Thread thread = new Thread(target,threadName);
        //设置为守护线程
        thread.setDaemon(true);
        return thread;
    }
}
